﻿using Rabbit.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using RabbitInfrastructure;

namespace Rabbit.Infrastructure.Implement
{
    /// <summary>
    /// 通用仓储实现类，封装基础的增删改查操作。
    /// </summary>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly MyDbContex _context;
      

        /// <summary>
        /// 构造函数，注入数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public BaseRepository(MyDbContex context)
        {
            _context = context;
        }

        /// <summary>
        /// 添加实体到数据库
        /// </summary>
        /// <param name="entity">要添加的实体对象</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> AddAsync(T entity)
        {
            await _context.Set<T>().AddAsync(entity);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取所有实体（只读）
        /// </summary>
        /// <returns>实体集合的 IQueryable，可用于进一步查询</returns>
        public IQueryable<T> GetAll()
        {
            return _context.Set<T>();
        }

        /// <summary>
        /// 更新实体信息
        /// </summary>
        /// <param name="entity">要更新的实体对象</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> UpdateAsync(T entity)
        {
            _context.Set<T>().Update(entity);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity">要删除的实体对象</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> DeleteAsync(T entity)
        {
            _context.Set<T>().Remove(entity);
            return await _context.SaveChangesAsync();
        }
    }
}
